package com.slipper.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot3.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class DruidConfiguration {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true")
    public FilterRegistrationBean<Filter> removeDruidAdFilter(DruidStatProperties properties) {
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String headerHtmlPattern = pattern.replaceAll("\\*", "header.html");
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");

        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter((request, response, chain) -> {
            chain.doFilter(request, response);

            String uri = ((HttpServletRequest) request).getRequestURI();
            if (uri.endsWith(headerHtmlPattern)) {
                parseHeaderHtml(response);
            } else if (uri.endsWith(commonJsPattern)) {
                parseCommonJs(response);
            }
        });
        registration.addUrlPatterns(headerHtmlPattern, commonJsPattern);
        return registration;
    }

    private void parseHeaderHtml(ServletResponse response) throws IOException {
        response.resetBuffer();
        String text = Utils.readFromResource("support/http/resources/header.html");
        text = text.replaceAll("<a[^>]*?alibaba[^>]*?>[^<]*?</a>", "");
        response.getWriter().write(text);
    }

    private void parseCommonJs(ServletResponse response) throws IOException {
        response.resetBuffer();
        String text = Utils.readFromResource("support/http/resources/js/common.js");
        text = text.replaceAll("<a.*?banner\"></a><br/>", "");
        text = text.replaceAll("powered.*?shrek.wang</a>", "");
        text = text.replaceAll("this.buildFooter\\(\\);", "// this.buildFooter();");
        response.getWriter().write(text);
    }
}
